package baseclass.e_tree;

/*

找前驱,分析找后继，然后和找后继的反过来
找前驱，就是要判断当前节点是否有左孩子。若有，则其有孩子的最右是。若没有，则循着父节点找，找到第一个右子树
    1)如当前节点有左孩子，则孩子的最右节点是前驱
    2)若当前节点没有左孩子，则当前节点一直往父节点走，直到某个节点是其父节点的右孩子。该父节点就是前驱
    特殊情况，中序遍历的第一个节点没有前驱。
 */

public class Code03_PreNode_前驱节点 {
    public static Node getPreNode(Node node) {
        if (node == null) return null;
        if (node.left != null) {
            return getRightestNode(node.left);
        }
        Node parent = node.parent;
        if (parent == null) return null;
        while (parent.right != node) {
            node = parent;
            parent = node.parent;
            if (parent == null) return null;
        }
        return parent;
    }

    private static Node getRightestNode(Node node) {
        while (node.right != null) node = node.right;
        return node;
    }


    public static void main(String[] args) {
        Node head = new Node(6);
        head.parent = null;
        head.left = new Node(3);
        head.left.parent = head;
        head.left.left = new Node(1);
        head.left.left.parent = head.left;
        head.left.left.right = new Node(2);
        head.left.left.right.parent = head.left.left;
        head.left.right = new Node(4);
        head.left.right.parent = head.left;
        head.left.right.right = new Node(5);
        head.left.right.right.parent = head.left.right;
        head.right = new Node(9);
        head.right.parent = head;
        head.right.left = new Node(8);
        head.right.left.parent = head.right;
        head.right.left.left = new Node(7);
        head.right.left.left.parent = head.right.left;
        head.right.right = new Node(10);
        head.right.right.parent = head.right;

        Node test = head.left.left; // 1's next is null
//        System.out.println(test.value + " next: " + getPreNode(test).value);
        test = head.left.left.right;
        System.out.println(test.value + " next: " + getPreNode(test).value);
        test = head.left;
        System.out.println(test.value + " next: " + getPreNode(test).value);
        test = head.left.right;
        System.out.println(test.value + " next: " + getPreNode(test).value);
        test = head.left.right.right;
        System.out.println(test.value + " next: " + getPreNode(test).value);
        test = head;
        System.out.println(test.value + " next: " + getPreNode(test).value);
        test = head.right.left.left;
        System.out.println(test.value + " next: " + getPreNode(test).value);
        test = head.right.left;
        System.out.println(test.value + " next: " + getPreNode(test).value);
        test = head.right;
        System.out.println(test.value + " next: " + getPreNode(test).value);
        test = head.right.right;
        System.out.println(test.value + " next: " + getPreNode(test).value);
    }


}
